package com.hugeyurt.util;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.*;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;
//import org.springframework.web.socket.server.standard.StandardWebSocketHandler;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    /**
     * 请求带有什么可以请求
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(customWebSocketHandler(), "/ws")
                .addInterceptors(customHandshakeInterceptor())
                .setAllowedOrigins("*"); // 允许所有域名跨域访问
    }

    @Bean
    public WebSocketHandler customWebSocketHandler() {
        return new CustomWebSocketHandler();
    }

    @Bean
    public HandshakeInterceptor customHandshakeInterceptor() {
        return new HandshakeInterceptor() {
            @Override
            public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                           WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
                if (request instanceof ServletServerHttpRequest) {
                    // 1. 此时请求对象有效，直接提取 username
                    ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
                    HttpServletRequest httpReq = servletRequest.getServletRequest();
                    String username = httpReq.getParameter("username"); // 握手阶段提取参数

                    // 2. 直接将 username 存入 attributes（而非存储整个请求对象）
                    attributes.put("PRE_EXTRACTED_USERNAME", username);
                    System.out.println("自定义拦截器：已提取并存储 username = " + username);
                }
                return true; // 允许握手继续
            }

            @Override
            public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                       WebSocketHandler wsHandler, Exception exception) {
                // 无需处理
            }
        };
    }
}